package one.stand.controller;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.feign.BannerFeign;
import com.jmp.service.api.admin.BannerApi;
import com.jmp.service.api.admin.dto.BannerListDto;
import com.jmp.service.api.admin.dto.BannerListVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.dto.*;
import one.stand.enums.SeeRecordEnums;
import one.stand.mapper.GoodsApiMapper;
import one.stand.mapper.SeeRecordPublicMapper;
import one.stand.model.Goods;
import one.stand.model.GoodsType;
import one.stand.model.ResultModel;
import one.stand.service.*;
import one.stand.util.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * @author cjr
 */
@Api(description = "首页")
@RestController
public class IndexController {

    @Autowired
    private BannerFeign bannerFeign;

    @Autowired
    private GoodsApiMapper goodsApiMapper;
    @Autowired
    private GoodsApiService goodsApiService;

    @Autowired
    private GoodsPhotoService goodsPhotoService;
    @Autowired
    private SeeRecordPublicMapper seeRecordPublicMapper;
    @Autowired
    private GoodsTypeService goodsTypeService;
    @Autowired
    private GoodsBaseService goodsBaseService;

    /**
     * @see 09/9/30 Deprecated. see {@link IndexController#index2}
     */
    @Deprecated
    @ApiOperation("首页")
    @GetMapping("index")
    @SecurityAuthCheck(company = true)
    public Result<IndexResponse> index(IndexRequest request) {
        final Integer companyId = RequestContextHolder.getRequestContext().getUser().getCompanyId();

        List<IndexResponse.Banner> banners = Lists.newArrayList();
        if (request.getPageNum() == 1) {
            BannerListDto bannerListDto = BannerListDto.builder()
                    .companyId(companyId)
                    .bannerType(BannerApi.BANNER_TYPE_IPAD)
                    .refId(null)
                    .build();
            bannerListDto.setAll();
            ResultModel<BannerListVo> bannerListVoResultModel = bannerFeign.list(bannerListDto);
            AssertUtil.isTrue(bannerListVoResultModel);
            banners = ConvertUtils.list(bannerListVoResultModel.getData().getBannerPage().getList(), companyBanner -> IndexResponse.Banner.builder()
                    .source(companyBanner.getSource())
                    .type(companyBanner.getType())
                    .event(String.valueOf(companyBanner.getEvent()))
                    .id(StringUtils.isNoneBlank(companyBanner.getEventId()) ? Integer.valueOf(companyBanner.getEventId()) : null)
                    .build());
        }

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<Goods> goodsModels = goodsApiMapper.selectIndex(companyId);

        PageResponse<IndexResponse.Goods> goodsPage = ConvertUtils.page(goodsModels, model -> {
            GoodsType goodsType = goodsTypeService.get(model.getGoodstypeId());
            String categoryName = goodsType.getGroupName().split(GoodsTypeService.SPLIT)[0];
            return IndexResponse.Goods.builder()
                    .id(model.getGoodsId())
                    .name(model.getGoodsName())
                    .price(PriceUtil.getPriceView2(model.getShowPrice() == 1, model.getPrice()))
                    .path(goodsPhotoService.getPath(model.getGoodsId()) + GoodsController.GOODS_IMAGE_SIZE)
                    .visitNum(seeRecordPublicMapper.selectCount(SeeRecordEnums.PRODUCT.getCode(), model.getGoodsId()))
                    .categoryName(categoryName)
                    .categoryName2(goodsType.getName())
                    .hasVr(StringUtils.isNoneBlank(model.getQjVrUrl()))
                    .hasVideo(StringUtils.isNoneBlank(model.getVideoUrl()))
                    .hasAr(goodsBaseService.hasAr(model.getGoodsId()))
                    .build();
        });

        IndexResponse indexResponse = IndexResponse.builder()
                .banner(banners)
                .goods(goodsPage)
                .build();
        return ResultUtil.success(indexResponse);
    }

    @ApiOperation("首页2")
    @GetMapping("index2")
    @SecurityAuthCheck(company = true)
    public Result<Index2Response> index2() {
        final Integer companyId = RequestContextHolder.getRequestContext().getUser().getCompanyId();

        BannerListDto bannerListDto = BannerListDto.builder()
                .companyId(companyId)
                .bannerType(BannerApi.BANNER_TYPE_IPAD)
                .refId(null)
                .build();
        bannerListDto.setAll();
        ResultModel<BannerListVo> bannerListVoResultModel = bannerFeign.list(bannerListDto);
        AssertUtil.isTrue(bannerListVoResultModel);
        List<Index2Response.Banner> banners = ConvertUtils.list(bannerListVoResultModel.getData().getBannerPage().getList(), companyBanner -> Index2Response.Banner.builder()
                .source(companyBanner.getSource())
                .type(companyBanner.getType())
                .event(String.valueOf(companyBanner.getEvent()))
                .id(StringUtils.isNoneBlank(companyBanner.getEventId()) ? Integer.valueOf(companyBanner.getEventId()) : null)
                .build());

        List<GoodsType> goodstypeModels = goodsApiMapper.selectListByCompanyId(companyId);


        Map<Integer, Integer> parentIds = Maps.newHashMap();
        int i = 0;
        List<Index2Response.Type> categories = Lists.newArrayList();
        if (OneListUtil.isNotEmpty(goodstypeModels)) {
            Index2Response.Type category;
            Index2Response.Type categoryChild;
            for (GoodsType goodstypeModel : goodstypeModels) {
                if (goodstypeModel.getParentId() == 0) {
                    parentIds.put(goodstypeModel.getGoodstypeId(), i++);
                    category = Index2Response.Type.builder()
                            .typeId(goodstypeModel.getGoodstypeId())
                            .typeName(goodstypeModel.getName())
                            .types(Lists.newArrayList())
                            .build();
                    categories.add(category);
                } else {
                    categoryChild = Index2Response.Type.builder()
                            .typeId(goodstypeModel.getGoodstypeId())
                            .typeName(goodstypeModel.getName())
                            .build();
                    int parentIndex = parentIds.get(goodstypeModel.getParentId());
                    categories.get(parentIndex).getTypes().add(categoryChild);
                    if (categories.get(parentIndex).getTypes().size() == 1) {
                        categories.get(parentIndex).setGoods(goodsApiService.categoryGoods(companyId, goodstypeModel.getGoodstypeId()));
                    }
                }
            }

//            categories = categories.stream().filter(type -> type.getTypes() == null || type.getTypes().size() > 0).collect(Collectors.toList());//过滤无二级分类的一级分类
        }

        Index2Response indexResponse = Index2Response.builder()
                .banner(banners)
                .types(categories)
                .build();
        return ResultUtil.success(indexResponse);
    }
}
